// pages/print/print.js
import WxValidate from "../../utils/WxValidate"
import utils from "../../utils/util"
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tempFile: [], //上传的临时文件 
    form: {
      filePath: [], //上传的文件数组 
      address: '请选择地址',
      pageNum: 1, //页数 
      mark: '', //备注信息 
      colorPrint: '黑白打印', //默认黑白打印 
      printPrice: 0.5, //黑白 
      doublePrint: '单面打印', //默认单面打印 
      payMoney: 3, //默认付款金额 
      runMoney: 3, //跑腿费3元 
    }
  },
  // 免责声明
  showStatment() {
    wx.showModal({
      title: '用户条款&隐私策略',
      content: '这里是隐私条款具体内容',
      showCancel: false
    })
  },

  //获取页面输入的页数 
  getPageNum(e) {
    const value = e.detail.value;
    if (value) {
      //计算金额 
      const {
        printPrice,
        runMoney
      } = this.data.form;
      //付款金额= 页数*每页打印单价 + 跑腿费 
      const payMoney = Number(value) * printPrice + runMoney;
      this.setData({
        'form.pageNum': value,
        'form.payMoney': payMoney
      })
    }
  },
    // 跳转到地址列表页
    toSelectedAAddress() {
      wx.navigateTo({
        url: '../address/address',
      })
    },
  //是否彩印 
  setReward(e) {
    const value = e.detail.value;
    //三元运算判断是否彩印 
    const colorPrint = e.detail.value ? '彩色打印' : '黑白打印';
    //三元运算设置打印单价 
    const printPrice = e.detail.value ? 1 : 0.5;
    let {
      runMoney,
      pageNum
    } = this.data.form;
    //根据打印单价，计算支付费用 
    const payMoney = Number(pageNum) * printPrice + runMoney;
    this.setData({
      'form.colorPrint': colorPrint,
      'form.printPrice': printPrice,
      'form.payMoney': payMoney
    })
  },
  //上传打印文件 
  uploadFile() {
    wx.chooseMessageFile({
      count: 3,
      type: 'file',
      success: async (res) => {
        wx.showLoading({
          title: '上传中...'
        })
        console.log(res)
        //遍历取得的文件的临时名称及路径信息，存入tempPath 
        const tempFile = res.tempFiles.map((item) => {
          return Object.assign({}, {
            name: item.name
          }, {
            path: item.path
          })
        })
        this.setData({
          tempFile
        })
        var successUp = 0; //成功 
        var failUp = 0; //失败 
        var length = res.tempFiles.length; //总数 
        var count = 0; //第几张 
        var filePath = []; //调用递归上传函数 
        this.uploadOneByOne(res.tempFiles, successUp, failUp, count, length, filePath);
        wx.hideLoading({})
      }
    })
  },
  /** * 采用递归的方式上传 */
  uploadOneByOne(imgPaths, successUp, failUp, count, length, filePath) {
    var that = this;
    wx.showLoading({
      title: '正在上传第' + count + '张',
    })
    wx.uploadFile({
      url: `${app.globalData.server}/uploadImg`,
      filePath: imgPaths[count].path,
      name: 'img',
      success: function (e) {
        let fileName = JSON.parse(e.data).path.replace(/\\/g, '/');
        // fileName = app.globalData.server+ '/' + fileName; 
        fileName = `${app.globalData.server}/${fileName}`
        filePath.push(fileName);
        successUp++; //成功+1 
      },
      fail: function (e) {
        failUp++; //失败+1 
      },
      complete: function (e) {
        count++;
        //下一张 
        if (count == length) {
          //上传完毕，作一下提示 
          console.log('上传成功' + successUp + ',' + '失败' + failUp);
          that.setData({
            'form.filePath': filePath
          })
          wx.showToast({
            title: '上传成功' + successUp,
            icon: 'success',
            duration: 2000
          })
        } else {
          //递归调用，上传下一张 
          that.uploadOneByOne(imgPaths, successUp, failUp, count, length, filePath);
          //console.log('正在上传第' + count + '张'); 
        }
      }
    })
  },
  //预览上传文件 
  viewFile(e) {
    console.log(e);
    const index = e.currentTarget.dataset.index;
    wx.openDocument({
      filePath: this.data.tempFile[index].path,
      success: function (res) {
        console.log('打开文档成功')
      }
    })
  },
  //备注信息 输入框防抖 
  timeID: 0, //定时器ID 
  handleInput(e) {
    const {
      value
    } = e.detail
    clearTimeout(this.timeID); //清楚timeID对应的定时器，即取消相应函数的执行 
    this.timeID = setTimeout(() => {
      this.setData({
        "form.mark": value
      })
    }, 500)
  },
  //是否双面 
  isDouble(e) {
    this.setData({
      'form.doublePrint': e.detail.value ? '双面打印' : '单面打印'
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.initValidate();
  },
  initValidate() {
    // 验证字段的规则 
    const rules = {
      filePath: {
        required: true
      },
      address: {
        required: true
      },
      pageNum: {
        required: true,
        digits: true
      },
      mark: {
        maxlength: 20
      }
    }
    // 验证字段的提示信息，若不传则调用默认的信息 
    const messages = {
      filePath: {
        required: '请上传文件',
      },
      address: {
        required: '请选择收货地址',
      },
      pageNum: {
        required: '请输入页数',
        digits: '只能输入数字'
      },
      mark: {
        maxlength: '最多不超过20字',
      }
    }
    // 创建实例对象 
    this.WxValidate = new WxValidate(rules, messages)
  },
  //提交表单 
  async submitForm() {
    //登录判断 
    const r = await utils.cklogin(app.globalData.userInfo)
    if (!r) {
      return false
    }
    const {
      filePath,
      address,
      pageNum,
      mark,
      colorPrint,
      doublePrint,
      payMoney
    } = this.data.form
    //console.log(this.data.form) 
    //需要验证 文件、地址选择、页数、备注 
    const formData = {
      filePath,
      address,
      pageNum,
      mark
    }
    //console.log(pageNum) 
    if (!this.WxValidate.checkForm(formData)) {
      const error = this.WxValidate.errorList[0]
      utils.showValidateModal(error)
      return false
    } else {
      wx.showLoading({
        title: '正在发布',
      })
      const publicTime = utils.formatTime(new Date());
      wx.request({
        url: `${app.globalData.server}/addOrder`,
        method: 'POST',
        data: {
          openid: app.globalData.userInfo.openid,
          orderType: '打印服务',
          endAddress: address, //目的地址 
          payMoney,
          status: '待帮助',
          publicTime,
          info: {
            filePath,
            pageNum,
            mark,
            colorPrint,
            doublePrint
          },
          userInfo: app.globalData.userInfo
        },
        success: res => {
          wx.hideLoading({})
          if (res.data == 'success') {
            wx.showToast({
              title: '提交成功',
              icon: 'success'
            })
            setTimeout(() => {
              wx.switchTab({
                url: '../order/order',
              })
            }, 1000);
          } else {
            wx.hideLoading({})
            wx.showToast({
              title: '发布失败',
              icon: 'error'
            })
          }
        },
        fail: err => {
          wx.hideLoading({})
          wx.showToast({
            title: '发布失败',
            icon: 'error'
          })
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})